package cronworker

import (
	"gitee.com/captials-team/ubdframe/src/common"
	"github.com/robfig/cron/v3"
)

type CronWorker interface {
	Cron() string
	Run()
}

func NewCronWorker(cron string, f func()) CronWorker {
	return &cronWorker{
		cron: cron,
		f:    f,
	}
}

type CronManager struct {
	c *cron.Cron

	workers []CronWorker
	running []cron.EntryID
}

func (mag *CronManager) Start() {
	for _, v := range mag.workers {
		eid, err := mag.c.AddJob(v.Cron(), v)
		common.ErrPanic(err)

		mag.running = append(mag.running, eid)
	}
	mag.c.Start()
}

func (mag *CronManager) Stop() {
	for _, eid := range mag.running {
		mag.c.Remove(eid)
	}
}

func (mag *CronManager) AddWorker(w CronWorker) {
	if w == nil {
		return
	}
	mag.workers = append(mag.workers, w)
}

func (mag *CronManager) Cron() *cron.Cron {
	return mag.c
}

func NewCronManager() *CronManager {
	return &CronManager{
		c: cron.New(),
	}
}

type cronWorker struct {
	cron string
	f    func()
}

func (w *cronWorker) Cron() string {
	return w.cron
}

func (w *cronWorker) Run() {
	w.f()
}
